package com.sunday.common.netty.e8_Handlerorder.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

@Slf4j
public class HandlerOrderTcpClient {

    public static final String SERVER_HOST = "127.0.0.1";

    public static final Integer SERVER_PORT = 8844;

    public static void main(String[] args) {

        /**
         * NioEventLoopGroup 是一个处理I/O操作的多线程事件循环。
         * Netty为不同类型的传输提供了各种EventLoopGroup实现。
         * EventLoopGroup 在编写时仅创建一个即可，过多资源浪费。
         */
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new HandlerOrderTcpClientChannel());
            ChannelFuture channelFuture = bootstrap.connect(SERVER_HOST, SERVER_PORT).sync();
            log.info("Client started.");

            log.info("Input message: ");

            while (true) {
                Scanner reader = new Scanner(System.in);
                String input = reader.nextLine();
                if ("quit".equalsIgnoreCase(input)) {
                    break;
                }
                channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(input, CharsetUtil.UTF_8));
            }

            channelFuture.channel().close();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            workerGroup.shutdownGracefully();
        }

    }

}
